package com.example.ssss;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.ssss.data.MysqlOperation;
import com.example.ssss.data.entity.ShareData;
import com.example.ssss.databinding.ActivityHistoryDetailBinding;
import com.example.ssss.entity.HistoryInfo;
import com.example.ssss.entity.LNH;
import com.example.ssss.entity.HistoryResponse;
import com.example.ssss.request.RequestHistoryViewModel;
import com.example.ssss.state.HistoryDetailViewModel;
import com.example.ssss.ui.home.HomeFragment;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HistoryDetailActivity extends AppCompatActivity {

    private LinearLayout heartHead,heartExpand;
    private ImageView heartArrow;
    private LineChart heartChart,oxyChart,pressureChart;
    private String behaveNameDemo[]={"打电话","未系安全带","打哈欠","低头","双手离开方向盘","闭眼"};
    private int[] behaveNumDemo ={1,2,1,4,2,1};
    private int index;

    ActivityHistoryDetailBinding binding;
    HistoryDetailViewModel stateViewModel;
    RequestHistoryViewModel requestHistoryViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent=getIntent();
        String index1=intent.getStringExtra("index");
        index=Integer.parseInt(index1);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_detail);

        String datestring=intent.getStringExtra("date");
        this.setTitle(datestring);

        initWorkspaceAction();
        heartHead=findViewById(R.id.heartHead);
        heartExpand=findViewById(R.id.heartExpand);
        heartArrow=findViewById(R.id.heartArrow);
        heartChart=findViewById(R.id.heartChart);
        oxyChart=findViewById(R.id.oxyChart);
        pressureChart=findViewById(R.id.pressureChart);
        ShareData shareData= (ShareData) getApplication();
        String userid=shareData.userId;
        showChartDemo(heartChart,"heart",userid);
        showChartDemo(oxyChart,"oxy",userid);
        showDualChartDemo(pressureChart,"pressure",userid);

        setCardExpand(R.id.heartHead,R.id.heartArrow,R.id.heartExpand);
        setCardExpand(R.id.behaveHead,R.id.behaveArrow,R.id.behaveExpand);
        setCardExpand(R.id.oxyHead,R.id.oxyArrow,R.id.oxyExpand);
        setCardExpand(R.id.pressureHead,R.id.pressureArrow,R.id.pressureExpand);

        //不安全动作列表初始化
        final ListView behaveList= (ListView) findViewById(R.id.behaveList);
        final TextView behaveNum=(TextView) findViewById(R.id.behaveTotalNum);
        List<Map<String, Object>> listItems=new ArrayList<Map<String, Object>>();
        int listLenth=behaveNameDemo.length;
        Integer count=0;
        new Thread(){
            @Override
            public void run() {
                super.run();

                MysqlOperation sql = new MysqlOperation();
                sql.behaveDao=new MysqlOperation.BehaveDao();
                try {
                    behaveNumDemo=sql.behaveDao.select(index,userid);
                    System.out.println("Mysql连接成功");

                    for (int i = 0; i < listLenth; i++) {
                        Map<String, Object> listItem=new HashMap<String,Object>();
                        listItem.put("behaveName", behaveNameDemo[i]);
                        listItem.put("behaveNum", behaveNumDemo[i]+" 次");
                        listItems.add(listItem);
//                        count=count+behaveNumDemo[i];
                    }
//                    behaveNum.setText(count.toString());


                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();
        SimpleAdapter simpleAdapter=new SimpleAdapter(this,listItems,R.layout.behave_list_item,new String[]{"behaveName","behaveNum"},new int[]{R.id.behaveItemName,R.id.behaveItemNum});
        behaveList.setAdapter(simpleAdapter);
        behaveList.setDividerHeight(3);

    }

    public void setCardExpand(int head,int arrow,int expand){

        LinearLayout Head=findViewById(head),Expand=findViewById(expand);
        ImageView Arrow=findViewById(arrow);
        Expand.setVisibility(View.GONE);

        Head.setOnClickListener(new View.OnClickListener() {//设置心率卡片展开或隐藏的监听
            @Override
            public void onClick(View view) {
                if(Expand.getVisibility()==View.GONE) {
                    Expand.setVisibility(View.VISIBLE);
                    Arrow.setImageResource(R.drawable.left);
                } else{
                    Expand.setVisibility(View.GONE);
                    Arrow.setImageResource(R.drawable.down);
                }

            }
        });
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg){
            LNH lnh= (LNH) msg.obj;
            if(lnh.getType().equals("heart")){
                View v=findViewById(R.id.heartLow);
                v.setLayoutParams(new LinearLayout.LayoutParams(0,
                        LinearLayout.LayoutParams.MATCH_PARENT, Float.parseFloat(lnh.getLow())));
                View v1=findViewById(R.id.heartNormal);
                v1.setLayoutParams(new LinearLayout.LayoutParams(0,
                        LinearLayout.LayoutParams.MATCH_PARENT, Float.parseFloat(lnh.getNormal())));
                View v2=findViewById(R.id.heartHigh);
                v2.setLayoutParams(new LinearLayout.LayoutParams(0,
                        LinearLayout.LayoutParams.MATCH_PARENT, Float.parseFloat(lnh.getHigh())));

                stateViewModel.heartnormal.setValue(lnh.getNormal());
                stateViewModel.heartlow.setValue(lnh.getLow());
                stateViewModel.hearthigh.setValue(lnh.getHigh());
            }else if(lnh.getType().equals("oxy")){
                View v=findViewById(R.id.oxyLow);
                v.setLayoutParams(new LinearLayout.LayoutParams(0,
                        LinearLayout.LayoutParams.MATCH_PARENT, Float.parseFloat(lnh.getLow())));
                View v1=findViewById(R.id.oxyNormal);
                v1.setLayoutParams(new LinearLayout.LayoutParams(0,
                        LinearLayout.LayoutParams.MATCH_PARENT, Float.parseFloat(lnh.getNormal())));
                View v2=findViewById(R.id.oxyHigh);
                v2.setLayoutParams(new LinearLayout.LayoutParams(0,
                        LinearLayout.LayoutParams.MATCH_PARENT, Float.parseFloat(lnh.getHigh())));

                stateViewModel.oxyhigh.setValue(lnh.getHigh());
                stateViewModel.oxynormal.setValue(lnh.getNormal());
                stateViewModel.oxylow.setValue(lnh.getLow());
            }else{
                View v=findViewById(R.id.pressureLow);
                v.setLayoutParams(new LinearLayout.LayoutParams(0,
                        LinearLayout.LayoutParams.MATCH_PARENT, Float.parseFloat(lnh.getLow())));
                View v1=findViewById(R.id.pressureNormal);
                v1.setLayoutParams(new LinearLayout.LayoutParams(0,
                        LinearLayout.LayoutParams.MATCH_PARENT, Float.parseFloat(lnh.getNormal())));
                View v2=findViewById(R.id.pressureHigh);
                v2.setLayoutParams(new LinearLayout.LayoutParams(0,
                        LinearLayout.LayoutParams.MATCH_PARENT, Float.parseFloat(lnh.getHigh())));

                stateViewModel.pressurehigh.setValue(lnh.getHigh());
                stateViewModel.pressurenormal.setValue(lnh.getNormal());
                stateViewModel.pressurelow.setValue(lnh.getLow());
            }
        }
    };
    static int[] dataDemo=new int[1005];
    static int[] dataDemo1=new int[1005];
    public void showChartDemo(LineChart chart,String s,String userid){
            new Thread(){
                @Override
                public void run() {
                    super.run();

                    MysqlOperation sql = new MysqlOperation();
                    sql.heartDao=new MysqlOperation.HeartDao();
                    try {
                        LNH lnh =new LNH();
                        lnh =sql.heartDao.select(s,index,userid);
                        System.out.println("Mysql连接成功");
                        dataDemo= lnh.getData();
                        Message message=new Message();
                        message.obj=lnh;
                        handler.sendMessage(message);


                        List<Entry> entries = new ArrayList<>();
                        for(int i=0;i<dataDemo.length;i++){
                            entries.add(new Entry(i,dataDemo[i]));
                        }
                        LineDataSet dataSet=new LineDataSet(entries,"demo");

                        //设置线条样式——一个dataset就是一条线
                        dataSet.setColor(Color.RED);
                        dataSet.setLineWidth(3);
                        dataSet.setCircleColor(Color.RED);
                        dataSet.setValueFormatter(new IValueFormatter() {
                            @Override
                            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                                return value + "次";
                            }
                        });
                        dataSet.setDrawValues(false);
                        LineData lineData=new LineData(dataSet);

                        chart.setData(lineData);//载入数据

                        //图标样式设置
                        //chart.setDrawGridBackground(false);//后台绘制
                        chart.getDescription().setEnabled(false);//设置描述文本
                        chart.getLegend().setEnabled(false);
                        chart.setTouchEnabled(true);//设置支持触控手势
                        chart.setDragEnabled(true);//设置缩放
                        chart.setScaleYEnabled(false);//设置允许x轴推动
                        chart.setNoDataText("暂无数据");
                        chart.setBorderColor(Color.YELLOW);
                        chart.setBorderWidth(2);
                        chart.getAxisLeft().setEnabled(false);//不绘制右侧y轴

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();


    }
    public void showDualChartDemo(LineChart chart,String s,String userid){
        new Thread(){
            @Override
            public void run() {
                super.run();

                MysqlOperation sql = new MysqlOperation();
                sql.heartDao=new MysqlOperation.HeartDao();
                try {
                    LNH lnh =new LNH();
                    lnh =sql.heartDao.select(s,index,userid);
                    System.out.println("Mysql连接成功");
                    dataDemo= lnh.getData();
                    dataDemo1=lnh.getData1();
                    Message message=new Message();
                    message.obj=lnh;
                    handler.sendMessage(message);
                    System.out.println("Mysql连接成功");
                    List<Entry> entries1 = new ArrayList<>();
                    List<Entry> entries2 = new ArrayList<>();
                    for(int i=0;i<dataDemo.length;i++){
                        entries1.add(new Entry(i,dataDemo[i]));
                        entries2.add(new Entry(i,dataDemo1[i]));
                    }
                    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
                    LineDataSet dataSet1=new LineDataSet(entries1,"demo");
                    LineDataSet dataSet2=new LineDataSet(entries2,"demo");

                    //设置线条样式——一个dataset就是一条线
                    dataSet1.setColor(Color.RED);
                    dataSet1.setLineWidth(3);
                    dataSet1.setCircleColor(Color.RED);
                    dataSet1.setValueFormatter(new IValueFormatter() {
                        @Override
                        public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                            return value + "mmHg";
                        }
                    });
                    dataSet1.setDrawValues(false);
                    dataSets.add(dataSet1);

                    dataSet2.setColor(Color.BLUE);
                    dataSet2.setLineWidth(3);
                    dataSet2.setCircleColor(Color.BLUE);
                    dataSet2.setValueFormatter(new IValueFormatter() {
                        @Override
                        public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                            return value + "mmHg";
                        }
                    });
                    dataSet2.setDrawValues(false);
                    dataSets.add(dataSet2);
                    chart.setData(new LineData(dataSets));//载入数据

                    //图标样式设置
                    //chart.setDrawGridBackground(false);//后台绘制
                    chart.getDescription().setEnabled(false);//设置描述文本
                    chart.getLegend().setEnabled(false);
                    chart.setTouchEnabled(true);//设置支持触控手势
                    chart.setDragEnabled(true);//设置缩放
                    chart.setScaleYEnabled(false);//设置允许x轴推动
                    chart.setNoDataText("暂无数据");
                    chart.setBorderColor(Color.YELLOW);
                    chart.setBorderWidth(2);
                    chart.getAxisLeft().setEnabled(false);//不绘制右侧y轴

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();


    }

    public void initWorkspaceAction(){
        stateViewModel=new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory()).get(HistoryDetailViewModel.class);
        requestHistoryViewModel=new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory()).get(RequestHistoryViewModel.class);

        //绑定databinding
        binding= DataBindingUtil.setContentView(this, R.layout.activity_history_detail);
        binding.setHistoryDetailVm(stateViewModel);
        binding.setLifecycleOwner(this);
        ShareData shareData=(ShareData)getApplication();
        requestHistoryViewModel.requestDataBase(index,shareData.userId);


        //observer
        observerDataStateUpdateAction();

    }





    private void observerDataStateUpdateAction() {
        requestHistoryViewModel.status.observe(this,new Observer<HistoryResponse>(){

            @Override
            public void onChanged(HistoryResponse historyResponse) {
                historyResponseUpdate(historyResponse);
            }
        });
    }

    private void historyResponseUpdate(HistoryResponse historyResponse) {
        stateViewModel.diaPres_avg.setValue(historyResponse.getDiaPres_avg());
        stateViewModel.concentration.setValue(historyResponse.getConcentration());
        stateViewModel.sysPres_avg.setValue(historyResponse.getSysPres_avg());
        stateViewModel.oxy_avg.setValue(historyResponse.getOxy_avg());
        stateViewModel.status.setValue(historyResponse.getStatus());
        stateViewModel.dangerousBehave.setValue(historyResponse.getDangerousBehave());
        stateViewModel.startAndEndTime.setValue(historyResponse.getStartAndEndTime());
        stateViewModel.heart_avg.setValue(historyResponse.getHeart_avg());
        stateViewModel.drivingTemp.setValue(historyResponse.getDrivingTemp());
        stateViewModel.drivingCO2.setValue(historyResponse.getDrivingCO2());
        stateViewModel.drivingTVOC.setValue(historyResponse.getDrivingTVOC());
        stateViewModel.drivingWet.setValue(historyResponse.getDrivingWet());
        stateViewModel.score.setValue(historyResponse.getScore());
    }



}